#!/bin/bash

# 检查是否提供了版本参数
if [ -z "$1" ]; then
    echo "错误：需要提供版本号！"
    echo "用法: ./deploy_servercheck.sh [版本号]"
    echo "示例: ./deploy_servercheck.sh 0.0.1"
    exit 1
fi

VERSION=$1
REGISTRY="mydockerregistry.tommickey.cn/tommickey/servercheck"
CONTAINER_NAME="servercheck"
CONFIG_FILE="config.yaml"
BASE_DIR="/docker/servercheck"

echo "开始部署 ServerCheck 版本: $VERSION"

# 1. 从镜像仓库拉取指定版本的镜像
echo "正在从镜像仓库拉取镜像..."
docker pull ${REGISTRY}:${VERSION}
if [ $? -ne 0 ]; then
    echo "拉取镜像失败！"
    exit 1
fi

# 2. 检查容器是否已存在，如果存在则停止并删除
if [ "$(docker ps -aq -f name=${CONTAINER_NAME})" ]; then
    echo "发现已存在的容器，正在停止并删除..."
    docker stop ${CONTAINER_NAME}
    docker rm ${CONTAINER_NAME}
fi

# 3. 创建配置目录
echo "创建配置目录..."
mkdir -p ${BASE_DIR}/config
mkdir -p ${BASE_DIR}/logs

# 4. 如果配置文件不存在，创建默认配置文件
if [ ! -f "${BASE_DIR}/config/${CONFIG_FILE}" ]; then
    echo "创建默认配置文件..."
    cat > "${BASE_DIR}/config/${CONFIG_FILE}" << EOF
email:
  smtp_server: "smtp.qq.com"
  smtp_port: 465
  username: "751020099@qq.com"
  password: ""  # 这里需要替换为您的QQ邮箱授权码
  from: "751020099@qq.com"
  to:
    - "751020099@qq.com"

servers:
  - name: "mk.tommickey.cn"
    url: "http://mk.tommickey.cn"
    check_interval: 43200
EOF
    echo "配置文件已创建在 ${BASE_DIR}/config/${CONFIG_FILE}"
fi

# 5. 创建并启动容器
echo "创建并启动容器..."
docker run -d \
    --name ${CONTAINER_NAME} \
    --restart unless-stopped \
    -v ${BASE_DIR}/config/${CONFIG_FILE}:/app/config.yaml \
    -v ${BASE_DIR}/logs:/app/logs \
    ${REGISTRY}:${VERSION}

if [ $? -ne 0 ]; then
    echo "容器启动失败！"
    exit 1
fi

echo "部署完成！"
echo "容器名称: ${CONTAINER_NAME}"
echo "配置文件位置: ${BASE_DIR}/config/${CONFIG_FILE}"
echo "日志文件位置: ${BASE_DIR}/logs/"
echo "使用 'docker logs ${CONTAINER_NAME}' 查看容器日志" 